/**
 * Created by liubin on 2014/11/13.
 */
define(['angular', 'controllers', 'role/roleService'], function(angular, controllers){
    'use strict';
    controllers.controller('roleListCtrl', ['$scope', '$location', '$window', 'DTOptionsBuilder','DTColumnBuilder',
     'roleListService', 'roleService', 'alertModalService', 'spinModalService', 'pageSize', 'actionColumnTemplate',
    function($scope, $location, $window, DTOptionsBuilder, DTColumnBuilder, roleListService, roleService,
             alertModalService, spinModalService, pageSize, actionColumnTemplate){
        $scope.table = null;
        $scope.dtOptions = DTOptionsBuilder.newOptions().
            withOption('dom',
            // 追加按钮行
            '<"toolbar">frtip').
            withOption('ajax', function(data, callback, settings){
                console.log(data);
                console.log(callback);
                console.log(settings);
                // 数据读取
                var roles = [];
                roleListService.get(
                    {
                        draw: data.draw,
                        size: pageSize,
                        start: data.start
                        // 查询
                        //query: $scope.query
                    },
                    {},  function (result){
                    angular.forEach(result.data, function (value, key) {
                        value.op = '';
                        roles.push(value);
                    });
                    //users =
                    console.log(result);
                    callback({
                        draw: result.draw,
                        data: roles,
                        recordsTotal: result.total,
                        recordsFiltered: result.total
                    });
                });
                //todo: add user get failure
            }).
            withOption('rowCallback', function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                // 增加按钮事件
                console.log(aData);
                //console.log($('a[action]', nRow));
                // 查看详细
                $('a[action=view]', nRow).bind('click', function(){
                    $scope.$apply(function() {
                        $scope.view(aData);
                    });
                });
                // 删除
                $('a[action=delete]', nRow).bind('click', function(){
                    $scope.$apply(function() {
                        $scope.delete(aData);
                    });
                });
                return nRow;
            }).
            withDataProp('data').
            withPaginationType('full_numbers');
        $scope.$on('event:dataTableLoaded', function(event, loadedDT) {

            // 追加按钮
            $("div.toolbar").html('<a class="btn col-sm-1 btn-danger" href="' + urlRoute.getUrl('role_add')
                + '" style="margin:0px 0px 3px 0px">新增</a>');
            // 宽度自适应
            var table = $("#" + loadedDT.id);
            $scope.table = table;
            $(window).resize(function(){
                table.attr('style',{'width': ''});
            });

        });
        $scope.dtColumns = [
            DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
            DTColumnBuilder.newColumn('code').withTitle('角色编码'),
            DTColumnBuilder.newColumn('name').withTitle('名称'),
            DTColumnBuilder.newColumn('op').withTitle('操作').renderWith(
                function(){
                    return actionColumnTemplate;
                }
            )
        ];
        $scope.view = function(data){
            console.log('view');
            console.log(data);
            var id = data.id;
            console.log(urlRoute.getUrl('role_view')+ '/' + id);
            $location.url(urlRoute.getUrl('role_view')+ '/' + id);
        }
        $scope.delete = function(data){
            console.log('delete');
            console.log(data);
            // 弹出框
            // 参数: 标题，内容，回调函数
            alertModalService.open('confirm', '确认', '你是否要删除该角色？', function(){
                console.log('do delete');
                spinModalService.open();
                roleService.delete({id: data.id}, {},
                function(success){
                    if (success.success) {
                        $window.location.href = urlRoute.getUrl('role_list');
                    }
                    else{
                        console.log(success.messages);
                        alertModalService.open('alert', '错误', success.messages[0]);
                    }
                    spinModalService.close();
                },
                function(error){
                    console.log('error');
                    alertModalService.open('alert', '错误', '服务器发生错误!');
                    spinModalService.close();
                });
            });
        }
    }]).controller('roleAddCtrl', ['$scope', '$window', 'roleListService', 'alertService', 'spinModalService',
        function($scope, $window, roleListService, alertService, spinModalService){
            $scope.add = function(e){
            console.log('add');
            console.log($scope.role);
            alertService.init($scope);

            spinModalService.open();
            roleListService.post(
                // get 参数
                {},
                // post参数
                {
                    code: $scope.role.code,
                    name: $scope.role.name
                },
                function (success) {
                    console.log(success);
                    if (success.success) {
                        $window.location.href = urlRoute.getUrl('role_list');
                    }
                    else{
                        console.log(success.messages);
                        angular.forEach(success.messages, function (value, key) {
                            alertService.addAlert({
                                msg:  value,
                                type: 'danger'
                            });
                        });
                    }
                    spinModalService.close();
                },
                function (error) {
                    //todo: add user get failure
                    console.log('error');
                    spinModalService.close();
                }
            );
        }
    }]).controller('roleViewCtrl', ['$scope', '$routeParams', '$q', '$location', 'roleService', 'alertService', 'spinModalService',
        function($scope, $routeParams, $q, $location, roleService, alertService, spinModalService){
        console.log('view');
        console.log($routeParams.id);
        var saveRole = function(data){
            console.log('saveRole');
            console.log(data);
            var d = $q.defer();
            roleService.put(
                {id: $routeParams.id},
                data,
                function (success) {
                    console.log(success);
                    if (success.success) {
                        d.resolve();
                    }
                    else{
                        var message = [];
                        angular.forEach(success.messages, function (value, key) {
                            message.push(value);
                        });
                        if(message){
                            d.resolve(message[0]);
                        }
                        else{
                            d.resolve('服务器错误!');
                        }
                    }
                },
                function(error){
                    console.log(error);
                    d.resolve('服务器错误!');
                }
            );
            return d.promise;
        }
        roleService.get(
            {id: $routeParams.id},
            {},
            function (success) {
                console.log(success);
                if (success.success) {
                    console.log(success.data);
                    $scope.role = success.data;
                    //$scope.getCompleted = true;
                }
                else {
                    //todo: add user get failure
                }
            }
        );
        $scope.updateCode = function(code){
            if(!code){
                return '编码不能为空!'
            }
            else{
                var data = angular.copy($scope.role);
                data.code = code;
                return saveRole(data);
            }
        };
        $scope.updateName = function(name){
            if(!name){
                return '名称不能为空!'
            }
            else{
                var data = angular.copy($scope.role);
                data.name = name;
                return saveRole(data);
            }
        };
    }]);
});